<!-- 车间管理 -->
<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">车间管理</div>
      <div class="search">
        <el-form
          :inline="true"
          :model="queryParams"
          ref="queryForm"
          @submit.native.prevent
        >
          <el-col :span="5">
            <el-form-item label="车间名称" prop="name">
              <el-input
                @keyup.enter.native="handleQuery"
                v-model="queryParams.name"
                placeholder="请输入车间名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['system:shop:add']"
            >新增</el-button
          >
        </div>
        <div class="ct-table">
          <elTables
            :table-data="tableData"
            :columns="tableColumns"
            :totalLength="total"
            :handle-current-change="handleCurrentChange"
            :currentPage="queryParams.pageNum"
            isPagin
            :curHeight="tableHeight"
          />
        </div>
      </div>
    </div>
    <!-- 添加或编辑车间管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      @close="cancel"
      class="dialog-form"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车间名称" prop="name">
              <el-input
                maxlength="30"
                v-model.trim="form.name"
                placeholder="请输入车间名称"
                :readonly="!isEdit"
                :disabled="!isEdit"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="责任部门" prop="deptId">
              <deptAndDuty
                type-show="dept"
                @deptChange="deptChange"
                :deptId="form.deptId"
                :disabled="!isEdit"
              ></deptAndDuty>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="负责人" prop="headUser">
              <deptAndDuty
                type-show="duty"
                @dutyChange="dutyChange"
                :deptId="form.deptId"
                :dutyId="form.headUser"
                :disabled="! isEdit "
              ></deptAndDuty>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-col :span="12">
          <el-form-item label="所属部门" prop="deptId">
            <el-input
              v-model="form.deptId"
              placeholder="请输入所属部门"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="headUser">
            <el-input
              v-model="form.headUser"
              placeholder="请输入负责人"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="自动带出"
              :readonly="true"
              :disabled="true"
              maxlength="11"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              maxlength="300"
              show-word-limit
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="厂区ID" prop="factoryId">
            <el-input
              v-model="form.factoryId"
              placeholder="请输入厂区ID"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="800px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { getToken } from "@/utils/auth";
import {
  pageShop,
  listShop,
  getShop,
  delShop,
  addShop,
  updateShop,
} from "@/api/system/shop";
import { getUser } from "@/api/system/user";
export default {
  name: "Shop",
  data() {
    return {
      tableHeight: 0,
      isEdit: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/shop/importData",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,

        name: null,
        deptId: null,
        headUser: null,
        phone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "车间名称不能为空", trigger: "blur" },
        ],
        // deptId: [
        //   { required: true, message: "所属部门不能为空", trigger: "blur" },
        // ],
        headUser: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
      },
      tableColumns: [
        { key: "name", title: "车间名称" },
        // { key: "deptIdName", title: "所属部门" },
        { key: "headUserName", title: "负责人" },
        { key: "phone", title: "联系方式" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["system:shop:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["system:shop:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2);
                    },
                  },
                },
                "查看"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["system:shop:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    this.getPage();
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    });
  },
  watch: {
    "form.headUser": {
      handler(val) {
        if (val) {
          this.$refs.form.clearValidate("headUser");
          getUser(val).then((res) => {
            this.form.phone = res.data.phonenumber;
          });
        }
      },
      deep: true,
      immediate: true,
    },
    "form.deptId": {
      handler(val) {
        if (val) {
          this.$refs.form.clearValidate("deptId");
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 组件传回的部门id
    deptChange(val) {
      this.form.deptId = val;
    },
    // 组件传回的人员id
    dutyChange(val) {
      this.form.headUser = val;
    },
    getTableHeight() {
      let height = document.getElementsByClassName("ct-table")[0].clientHeight;
      this.tableHeight = height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询车间管理列表 */
    getPage() {
      this.loading = true;
      pageShop(this.queryParams).then((response) => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        deptId: null,
        headUser: null,
        phone: null,
        remark: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = true;
      this.title = "新增车间管理";
    },
    /** 编辑按钮操作 */
    handleUpdate(row, type) {
      if (type == 1) {
        this.isEdit = true;
        this.title = "编辑车间管理";
      } else {
        this.isEdit = false;
        this.title = "查看车间管理";
      }
      this.reset();
      const id = row.id || this.ids;
      getShop(id).then((response) => {
        this.form = response.data;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateShop(this.form).then((response) => {
              this.msgSuccess("编辑成功");
              this.open = false;
              this.getPage();
            });
          } else {
            addShop(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          let data;
          if (Array.isArray(ids)) {
            data = ids;
          } else {
            data = [ids];
          }
          return delShop(data);
        })
        .then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-form {
  // .el-col {
  //   float: right !important;
  // }
}
</style>
